<!-- 员工页面 -->
<template>
  <div class="container">
    <div class="app-container">
      <el-row type="flex">
        <!-- 左 -->
        <el-card class="el_card_left">
          <!-- 输入框模糊搜索: 双向绑定v-model与监听@input事件 -->
          <el-input
            v-model="pageParams.keyword"
            placeholder="输入员工姓名全员搜索"
            prefix-icon="el-icon-search"
            style="margin-bottom: 10px"
            size="small"
            @input="inputKeyword"
          />
          <!--  highlight-current选中节点高亮
                 node-key="id"唯一值, 配合setCurrentKey方法使用
                 @current-change当前选中节点变化时触发的事件-->
          <el-tree
            ref="tree"
            :data="treeData"
            :props="{ label: 'name' }"
            default-expand-all
            :expand-on-click-node="false"
            node-key="id"
            highlight-current
            @current-change="treeCurrentChange"
          />
        </el-card>

        <!-- 右 -->
        <el-card class="el_card_right">
          <el-row type="flex" justify="space-between">
            <el-button size="small">群发通知</el-button>

            <!-- 右 -->
            <el-row>
              <el-button type="primary" size="small" @click="testDownload">测试下载功能</el-button>
              <el-button type="primary" size="small" @click="$router.push('/employee/detail')">添加员工</el-button>
              <el-button size="small" @click="showExcelDialog=true">excel导入</el-button>
              <el-button size="small" @click="exportExcel">excel导出</el-button>
            </el-row>
          </el-row>
          <!-- header-cell-style表头背景色 -->
          <el-table
            :data="tableData"
            :header-cell-style="{ backgroundColor: '#F5F6F8' }"
          >
            <el-table-column type="selection" width="48" align="center" />
            <el-table-column label="头像" prop="staffPhoto" width="114" align="center">
              <!-- 条件渲染头像-插槽 -->
              <template #default="{row:{ staffPhoto, username }}">
                <el-avatar v-if="staffPhoto" :src="staffPhoto" />
                <el-row v-else type="flex" justify="center">
                  <div class="username">{{ username && username.charAt(0) }}</div>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column label="姓名" prop="username" width="114" align="center" />
            <el-table-column label="手机号" sortable prop="mobile" width="110" align="center" />
            <el-table-column label="工号" sortable prop="workNumber" width="110" align="center" />
            <el-table-column label="聘用形式" prop="formOfEmployment" width="110" align="center">
              <template #default="{row}">
                {{ row.formOfEmployment===1? '正式':'非正式' }}
              </template>
            </el-table-column>
            <el-table-column label="部门" prop="departmentName" width="110" align="center" />
            <el-table-column label="入职时" sortable prop="timeOfEntry" width="110" align="center" />
            <el-table-column label="操作" prop="date" align="center">
              <template #default="{ row:{ id } }">
                <!-- v-permission自定义指令, detail给自定义指令设置一个值 -->
                <el-button v-permission="'detail'" type="text" size="medium" @click="$router.push(`/employee/detail/${id}`)"> 查看 </el-button>
                <el-button v-permission="'role'" type="text" size="medium" @click="onShowRoleList(id)"> 角色 </el-button>
                <el-popconfirm title="确认删除吗?" @onConfirm="onConfirmDelete(id)">
                  <template #reference>
                    <el-button v-permission="'del'" type="text" size="medium"> 删除 </el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <el-row type="flex" justify="center" style="height: 60px;" align="middle">
            <!-- 分页 -->
            <el-pagination
              layout="prev, pager, next"
              :total="pageParams.total"
              :current-page="pageParams.page"
              @current-change="currentChange"
            />
          </el-row>
        </el-card>
      </el-row>
    </div>

    <!-- 员工导入对话框 -->
    <ImportExcel :show-excel-dialog.sync="showExcelDialog" />

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="roleShowDialog">
      <el-checkbox-group v-model="roleIds">
        <!-- label分配的是id, 用插值符写权限名字 -->
        <el-checkbox v-for="v in checkList" :key="v.id" :label="v.id">{{ v.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row type="flex" justify="center" style="margin-top: 20px;">
        <el-button type="primary" size="mini" @click="onSaveRole">确定</el-button>
        <el-button size="mini">取消</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getDepartmentAPI } from '@/api/department'
import { delEmployeeAPI, exportExcelAPI, getEmployeeAPI, getEmployeeDetailAPI, putAssignRolesAPI } from '@/api/employee'
import { arrayToTree } from '@/utils'
import { saveAs } from 'file-saver'
import ImportExcel from './import-excel.vue'
import { getEnabledAPI } from '@/api/permission'

export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      treeData: [], // 部门列表tree
      tableData: [], // 表格数据
      pageParams: { // 接口参数
        page: 1,
        pagesize: 10,
        keyword: '', // 输入框
        departmentId: null,
        total: 0
      },
      showExcelDialog: false, // excel导入对话框
      roleShowDialog: false, // 分配角色对话框
      roleIds: [], // 分配权限收集的id, -存储员工的角色权限id, 用于回显选中复选框
      checkList: [] // 角色弹出框里的数据
    }
  },
  created() {
    this.getTreeData()
  },
  methods: {
    // 获取部门列表-tree
    async getTreeData() {
      const res = await getDepartmentAPI()
      this.treeData = arrayToTree(res) // 1.1 渲染部门列表
      this.pageParams.departmentId = this.treeData[0].id // 1.4 存储tree的第一个节点id
      this.getEmployeeData() // 1.5 拿到此部门的id, 渲染表格

      // 1.2 等tree的dom更新完毕, 调用setCurrentKey方法, 把当前节点的id传进去
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.treeData[0].id)
      })
    },
    // 1.3 获取员工列表
    async getEmployeeData() {
      const { rows, total } = await getEmployeeAPI(this.pageParams)
      this.tableData = rows
      this.pageParams.total = total
    },
    // 1.6 tree当前选中节点变化时触发的事件
    treeCurrentChange(data) {
      // 1.7 存储部门id, 并刷新表格
      this.pageParams.departmentId = data.id
      this.getEmployeeData()
    },

    // 切换页数
    currentChange(page) {
      this.pageParams.page = page
      this.getEmployeeData() // 刷新表格
    },

    // 输入框模糊搜索
    inputKeyword() {
      // 注解: 因为timerId 不是响应式, 可以直接挂在this上(等价于挂在window上)
      clearTimeout(this.timerId)
      // 注解: JS 弱类型, 主要是对象, 都可以随意分配新属性
      this.timerId = setTimeout(() => {
        // 2.1 先重置为第一页, 再发请求开始搜索, 因为搜索时, 需要从第一页开始搜索才是正确的
        this.pageParams.page = 1
        this.getEmployeeData()
      }, 500)
    },
    // 导出功能Excel文件
    async exportExcel() {
      // 发请求,拿到数据,下载文件
      /* 后端返回的格式
          Blob {size: 17955, type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      */
      const blob = await exportExcelAPI()
      // saveAs(blob类型, 文件名.格式)
      saveAs(blob, '员工信息.xlsx') // res 为blob类型, 第二个参数为文件名, 后端返回的什么格式
    },
    // 下载功能
    testDownload() {
      // [下载文件]
      // const blob = new Blob(['Hello, world!'], { type: 'text/plain;charset=utf-8' })
      // saveAs(blob, 'xxx.txt') // xxx.txt 为文件名
      // 下载图片
      saveAs('https://lf-flow-web-cdn.doubao.com/obj/flow-doubao/samantha/logo-icon-white-bg.png', 'xxx.png') // xxx为文件名, png为格式, 图片是什么格式, 就下载成什么格式!!!
    },
    // 删除功能
    async onConfirmDelete(id) {
      await delEmployeeAPI(id)
      // 如果此页面只剩余1条数据, 并且当前页大于1, 则页码减1(自动回退到上一页)
      if (this.tableData.length === 1 && this.pageParams.page > 1) {
        this.pageParams.page--
      }
      this.getEmployeeData() // 刷新页面
      this.$message.success('删除成功')
    },

    // 点击角色按钮
    async onShowRoleList(id) {
      this.checkList = await getEnabledAPI() // 获取-已启用的角色列表
      const { roleIds } = await getEmployeeDetailAPI(id) // 获取员工的基本信息-里面有员工的角色权限
      this.roleIds = roleIds // 存储员工的角色权限id, 用于回显选中复选框
      this.roleShowDialog = true
      this.employeeId = id // 动态存储员工id
    },
    // 点击确定按钮-分配角色
    async onSaveRole() {
      await putAssignRolesAPI({ roleIds: this.roleIds, id: this.employeeId })
      this.$message.success('分配角色成功')
      this.roleShowDialog = false
    }
  }
}
</script>
<style lang="scss" scoped>
.el_card_left{
  width: 263px;
}
.el_card_right{
  flex: 1;
}
.username{
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #04C9BE;
  color: #fff;
  text-align: center;
  line-height: 40px;
}

</style>
